using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class RedPointMgr
{
    private static RedPointMgr _instance;
    public RedPointNode root;

    public static RedPointMgr Instance
    {
        get
        {
            if (_instance == null)
            {
                _instance = new RedPointMgr();
            }

            return _instance;
        }
    }

    private RedPointMgr()
    {
    }

    private Dictionary<ulong, RedPointNode> allRedPointNodes = new Dictionary<ulong, RedPointNode>();

    public void Init()
    {
        if (allRedPointNodes.Count == 0)
        {
            root = new RedPointNode("root");
            
            var names = Enum.GetNames(typeof(ERedPoint));

            foreach (string name in names)
            {
                int index = name.LastIndexOf('_');
                if (index > 0)
                {
                    var parStr= name.Substring(0, index);
                    var eRedPoint = GetPointTypeByTypeStr(parStr);
                    if (allRedPointNodes.TryGetValue((ulong)eRedPoint, out RedPointNode node))
                    {
                        var eRedChild = GetPointTypeByTypeStr(name);
                        var childNode= node.GetOrAddRedPointNode(eRedChild);
                        allRedPointNodes.Add(childNode.Id,childNode);
                    }
                }
                else
                {
                    var eRedPoint = GetPointTypeByTypeStr(name);
                    if (eRedPoint == ERedPoint.None) continue;
                    if (!allRedPointNodes.TryGetValue((ulong)eRedPoint, out RedPointNode node))
                    {
                        node = root.GetOrAddRedPointNode(eRedPoint);
                        allRedPointNodes.Add(node.Id,node);
                    }
                }
            }
        }
    }

    public ERedPoint GetPointTypeByTypeStr(string eRedPoint)
    {
        return Enum.Parse<ERedPoint>(eRedPoint);
    }

    public RedPointNode GetNode(ERedPoint eRedPoint)
    {
        return GetNode((ulong)eRedPoint);
    }

    public RedPointNode GetNode(ulong eRedPoint)
    {
        allRedPointNodes.TryGetValue(eRedPoint, out RedPointNode node);
        return node;
    }

    public void Release()
    {
        foreach (var allRedPointNode in allRedPointNodes)
        {
            allRedPointNode.Value.Release();
        }

        allRedPointNodes.Clear();
        root = null;
    }
}